package com.ccx.coachsite.downloadmgr;


import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class AsyncImageLoaderStatic {

	 private static ExecutorService executorService = Executors.newCachedThreadPool(); 

	 private static HashMap<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();	
	  
     public static Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
         if (imageCache.containsKey(imageUrl)) {
             SoftReference<Drawable> softReference = imageCache.get(imageUrl);
             Drawable drawable = softReference.get();
             if (drawable != null) {
                 return drawable;
             }
         }
         final Handler handler = new Handler() {
             public void handleMessage(Message message) {
                 imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
             }
         };
         
         Thread t = new Thread() {
             @Override
             public void run() {
                 Drawable drawable = ImageCacheTool.loadImageFromUrl(imageUrl);
                 imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                 Message message = handler.obtainMessage(0, drawable);
                 handler.sendMessage(message);
             }
         };
         //t.start();
         executorService.execute(t);	         
         return null;
     }
  
    public interface ImageCallback {
       public void imageLoaded(Drawable imageDrawable, String imageUrl);
    }	
    
    public static void releaseImageCache(){
    	if (imageCache==null) return;
    	int i=1;
    	for (SoftReference<Drawable> softReference : imageCache.values()) {
    		 System.out.println(i++);
             Drawable drawable = softReference.get();
             if (drawable != null) {
            	 drawable.setCallback( null );
             }else{
            	 System.out.println("已被回收");
             }
    	}
    	
    	imageCache.clear();	    	 
    }

}
